<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request; 
use App\Model\{Admin,User,Config,Productcat,Product,Productattr}; 
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
#use App\Libraries\vendor\Img;
/**
 * @menu_cat 产品列表
 * @icon user
 * @sort 30
 */
class ProductController extends Controller
{
	public $news_valid = [
        'title' => 'required',
        'cat_id' => 'nullable',
        'summary'=>'nullable',
        'pos'=>'integer',
        'stock'=>'required|integer',
        'price'=>['required','money'],
        'content' => 'required',
        'img'=>'nullable',
        'thumb_img'=>'nullable',
        'attr_id'=>'nullable',
        'val'=>'nullable',
        'ids'=>'nullable',
        'specifications'=>'nullable'
    ];
    public $accept = ['title', 'cat_id', 'content','summary', 'specifications' ,'add_date','img','thumb_img','pos','stock','price','attr_id','val','ids'];

    public function __invoke(){
        return $this->index(func_get_args());
    }

    /**
     * @menu 产品列表
     * @author wudi
     */
    public function index($id=NULL){
        $list = DB::table('product');
        $this->_search($list, $search);
        $total = $list->count();
        $this->_order($list, ['id'=>'desc']);
        $list = $list->paginate(20);
        foreach($list->items() as &$item){
            $item->img = explode('|',$item->img);
        }


        #$cat_ids = get_array_keys($list->items(),'cat_id');
        #$cats = DB::table('product_cat')->select('id','cat_name')->whereIn('id',$cat_ids)->get()->toArray();

        return view('Admin.Product.index')->with([
            'list' => $list,
            '_search'=>$search,
            #'cats'=>arrays_set_key($cats,'id'),
        ]);
    }

    /**
     * @menu 添加产品
     * @author wudi
     */
    public function add(){
        if(request()->isMethod('get')){
        	/*
        	$cat_id = isset($_GET['cat_id'])?intval($_GET['cat_id']):0;
        	if(!$cat_id){
        		return view('Admin.Product.selectcat',[
        				'cat'=>arrays_set_key(Productcat::get_all_child(),'id'),
        			]);
        	}

            $cat_info = DB::table('product_cat')->where('id',$cat_id)->first(['type_id']);
			
        	$html = view('Admin.Product.attr_input',[
        			'attr'=>Productattr::get_attr(['type_id'=>$cat_info->type_id]),
        		]);
        	$html = response($html)->getContent();
        	*/
            return view('Admin.Product.add')->with([
                #'cat'=> arrays_set_key(Productcat::get_all_child(),'id'),
                #'cat_id'=>$cat_id,
                #'html'=>$html,
            ]);
        }
        $this->validate(request(), $this->news_valid);
        $param = request()->only($this->accept);
        $param['add_date'] = date('Y-m-d H:i:s');

        $attr_id = $param['attr_id']??[];
        $val = $param['val']??[];
        unset($param['attr_id']);
        unset($param['val']);
        $product_id = DB::table('product')->insertGetId($param);

        #$cat_info = DB::table('product_cat')->where('id',$param['cat_id'])->first(['type_id']);
        #$bool = Product::add_attr($product_id,$cat_info->type_id,$attr_id,$val);
        if($bool && $param['img']){
            #缩略图
            $imgs = explode('|',$param['img']);
            /*
            $obj = new Img();
            foreach($imgs as $img){
                $oimg = public_path().'/'.$img;
                $toimg = suffix($oimg,'_200');
                $obj->thumb_cut($oimg,238,318,$toimg);
            }
            */
        }
        return redirect('/Product');
    }

    /**
     * @name 编辑产品
     * @author wudi
     */
    public function edit($id){
        if(request()->isMethod('get')){
            $data = DB::table('product')->where('id',$id)->first();
            if(!$data){ abort(404); }
            $data->img = explode('|',$data->img);
            #$cat_info = DB::table('product_cat')->where('id',$data->cat_id)->first(['type_id']);
            /*
            $html = view('Admin.Product.attr_input',[
        			'attr'=>Productattr::get_attr(['type_id'=>$cat_info->type_id]),
        			'attrs'=>Productattr::get_attr_vals(['product_id'=>$id]),
        			'edit'=>true,
        		]);
			*/
            return view('Admin.Product.edit')->with([
                'data'=>$data,
                #'cat'=>Productcat::get_all_child(),
                'html'=>'',//$html,
            ]);
        }
        $this->validate(request(), $this->news_valid);
        $param = request()->only($this->accept);

        #$attr_id = $param['attr_id']??[];
        #$val = $param['val']??[];
        #$ids = $param['ids']??[];
        #unset($param['attr_id']);
        #unset($param['val']);
        #unset($param['ids']);
        #$rs = Product::updat_attr($attr_id,$val,$ids,$id);

        #图片处理
        if(empty($param['img'])){
            unset($param['img']);
        }else{
            $old_img = DB::table('product')->where('id',$id)->first(['img']);
            
            #is_file($old_img->img) && unlink($old_img->img);
            #缩略图
            #$imgs = explode('|',$param['img']);
            #$obj = new Img();
            #foreach($imgs as $img){
            #    $oimg = public_path().'/'.$img;
            #    $toimg = suffix($oimg,'_200');
            #    $obj->thumb_cut($oimg,238,318,$toimg);
            #}
        }

        if(empty($param['thumb_img'])) {
            unset($param['thumb_img']);
        }

        DB::table('product')->where('id',$id)->update($param);
        return redirect('/product/edit/'.$id);
    }


    public function ajax_delete_thumb(){
        $param = request()->only(['id','img']);
        $info = DB::table('product')->where('id',$param['id'])->first(['img']);
        $imgs =  empty($info->img)?[]:explode('|',$info->img);
        $final = "";
        foreach($imgs as $img){
            if( img($img)==img($param['img'])){
                /*
                $item1 = public_path().img($img);
                $item2 = public_path().img(suffix($img,'_200'));
                if(is_file($item1)){
                    unlink($item1);
                }
                if(is_file($item2)){
                    unlink($item2);
                }
                */
            }else{
                $final .= $img.'|';
            }
        }
        $final = rtrim($final,'|');
        DB::table('product')->where('id',$param['id'])->update(['img'=>$final]);
        return response()->json([
                'status'=>1,
                'img'=>$final
            ]);
    }
}